package com.jason.learn.springcloud.searchservice.service;

import com.jason.learn.springcloud.searchservice.dto.PageResult;
import com.jason.learn.springcloud.searchservice.enty.BuyOrder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class EsBuyOrderService {
    @Autowired
    private ElasticsearchRestTemplate esRestTemplate;

    public PageResult<BuyOrder>  searchBuyOrder(Date queryBeginDate, Date queryEndDate, int page, int pageSize){
        RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("create_time");
        queryBuilder.gte(queryBeginDate);
        queryBuilder.lte(queryEndDate);
        PageRequest pageRequest = PageRequest.of(page-1,pageSize);
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(pageRequest)
                .build();
        SearchHits<BuyOrder> searchHits= esRestTemplate.search(searchQuery, BuyOrder.class);

        PageResult<BuyOrder> result = new PageResult();
        result.setTotal(esRestTemplate.count(searchQuery, BuyOrder.class));
        List<BuyOrder> buyOrders = new ArrayList<>();
        for(SearchHit<BuyOrder> searchHit : searchHits) {
            buyOrders.add(searchHit.getContent());
        }
        result.setData(buyOrders);
        return result;
    }
}
